import React, { useEffect, useState } from "react";
import { BoxComp } from "@/components/pages/lottery/comp";
import { Button, Modal, Space, Toast } from "antd-mobile";
import requewt from "@/utils/requewt";
import { API } from "@/config/api";
import classnames from "classnames";
import callFeedback from "@/components/common/modalFeedback";
import useRecord from "@/components/pages/stores/useRecord";
import { useRouter } from "next/router";
import { AddressComp } from "@/components/common";
import { motion } from "framer-motion";

const pageName = "lottery";
const klassName = pageName.replace(/\./g, '-');


export default function Page(props) {

  const [opens, setOpens] = useState([]);
  const [out, setOut] = useState(false);
  const [loading, setLoading] = useState(false);
  const [remain, setRemain] = useState(0);
  const lotterys = useRecord(state => state.lotterys);
  const update = useRecord(state => state.update);

  const  celebrate = () => {
    const box = document.getElementById(`box`);

    let count = 200;
    let defaults = {
      zIndex: 9999,
      origin: {
        x: 0.5,
        // since they fall down, start a bit higher than random
        y: .5 || 0
      }
    };

    function fire(particleRatio, opts) {
      confetti(
        Object.assign({}, defaults, opts, {
          particleCount: Math.floor(count * particleRatio)
        })
      );
    }

    fire(0.25, {
      spread: 26,
      startVelocity: 55
    });
    fire(0.2, {
      spread: 60
    });
    fire(0.35, {
      spread: 100,
      decay: 0.91,
      scalar: 0.8
    });
    fire(0.1, {
      spread: 120,
      startVelocity: 25,
      decay: 0.92,
      scalar: 1.2
    });
    fire(0.1, {
      spread: 120,
      startVelocity: 45
    });
  }

  const router = useRouter();

  useEffect(() => {
    (async () => {
      await handler.check()
    })()
  }, [])


  const {user} = props;

  let {remain_num = 0} = user || {};

  let data = [];
  for (let i = 0; i < 9; i++) {
    data.push(i)
  }


  const handler = {
    // 检测抽奖次数
    check: async () => {
      const resp = await requewt(API.lottery.remain);
      if (resp?.error_code !== 0 || resp?.msg !== `ok`) {
        return
      }
      update(`lotterys`, resp.data?.remain_draw_num);
    },
    select: async (index) => {
      console.log(`index`, index);
      if (!lotterys) {
        const r = callFeedback({
          bodyClassName: `act-feedback-modal close-at-center-bottom`,
          title: <>很遗憾</>,
          content: <>您今日的抽奖机会已用完</>,
          actions: <></>,
          closeOnAction: true,
          closeOnMaskClick: false,
        })
        return
      }

      await handler.lottery(index)
    },
    lottery: async index => {
      if (loading) return;
      setLoading(true);

      Toast.show({content: `抽取中...`, icon: `loading`});
      const options = {method: `POST`}
      const resp = await requewt(API.lottery.draw, options);
      await Toast.clear();
      setLoading(false)
      console.log(`resp`, resp);
      if (resp?.[`error_code`] !== 0 || resp?.[`msg`] !== `ok`) {
        Toast.show({content: resp?.[`msg`] || `抽取失败`, icon: `fail`});
        return
      }

      const item = resp.data;
      update(`lotterys`, item?.today_remain_draw_num);

      if (item?.category === 5) {
        const m = callFeedback({
          bodyClassName: `act-feedback-modal close-at-center-bottom`,
          content: <div className="text-center">
            <div className="p-3">
              <img className="img-fluid" width={150} src="/img/prize/prize-fail.png" alt="" />
            </div>
            <div>
              很遗憾您未能抽中奖品 <br />
              再来一局，好运降临
            </div>
          </div>,
          actions: [
            <Button size={`small`} shape="rounded"
                    onClick={e => m.close()}
                    className={`act-btn act-btn-normal`}
            >
              再来一局
            </Button>
          ]
        })
        return
      }

      const c = callFeedback({
        bodyClassName: `act-feedback-modal cp-lottery-modal close-hidden`,
        content: <div className="inner">

          <div className="content">
            <img className="img-fluid" src={item.icon} alt="" />
            <div className="lottery-result-title">
              {item?.status !== 0 && `恭喜您获得 `}{item.reward_name}
            </div>
          </div>
          <div className="operation">
            {
              item?.category === 0 &&
              <Button block
                      onClick={e => {
                        handler.address(item);
                        // clearInterval(timer);
                      }}
                      shape={`rounded`}
                      size="small"
                      className="act-btn act-btn-normal">填写收货地址</Button>
            }

            <Button shape={`rounded`} size="large" style={{width: 175}}
                    onClick={e => {
                      c.close();
                      router.push(`/prize`)
                    }}
                    className="act-btn act-btn-bevel"
            >
              返回我的奖品
            </Button>
          </div>
        </div>,
        actions: <></>,
        closeOnAction: false,
        closeOnMaskClick: false,
      })

      setTimeout(() => celebrate(), 300);
      setTimeout(() => setOut(true), 1500)
      // const timer = setInterval(() => celebrate(), 3000);
    },
    address: (item) => {
      const m = callFeedback({
        bodyClassName: `address-modal-body`,
        content: <>
          <AddressComp data={item} handler={handler} />
        </>,
        actions: <></>
      })
    },
    filled: () => {
      Modal.clear();
    }
  }

  return (
    <div className={`p-${klassName} page page-sec`}>
      <div className="inner">
        <div className="position-center">
          <motion.img animate={{
            y: [0, 10, 0, -10, 0],
            transition: {
              duration: 5,
              repeat: Infinity,
              ease: `linear`
            }
          }} className="img-fluid" src="https://yinli-qixi-run.varwey.com/2023/3w-jump-alien-230703/img/lottery/cube-planet.png" alt="" />

          <Space>
            <Button shape={`rounded`} size={`large`}
                    className="act-btn act-btn-bevel"
                    onClick={e => router.replace(`/prize`)}
            >
              返回
            </Button>

            <Button shape={`rounded`} size={`large`}
                    className="act-btn act-btn-bevel"
                    onClick={e => handler.lottery()}
            >
              点击抽奖
            </Button>
          </Space>

        </div>
      </div>
    </div>
  )
}


Page.need2auth = true;
Page.pageName = pageName;